﻿using System.Data.Common;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Tool.hbm2ddl;

namespace Command.Commands
{
	public abstract class BaseDatabaseCommand : BaseCommand<Options>
	{
		private readonly Configuration _configuration;
		private readonly ISession _session;

		protected BaseDatabaseCommand(Configuration configuration, ISession session)
		{
			_configuration = configuration;
			_session = session;
		}

		protected override void InternalExecute(Options options)
		{
			Dialect dialect = new MsSql2008Dialect();
			var conn = _session.Connection;
			var metadata = new DatabaseMetadata((DbConnection) conn, dialect);
			var sql = GenerateStatements(_configuration, dialect, metadata);
			if (sql != null && sql.Length > 0)
			{
				foreach (var step in sql)
				{

					using (var cmd = conn.CreateCommand())
					{
						cmd.CommandText = step;
						cmd.ExecuteNonQuery();
					}
				}
			}
		}

		protected abstract string[] GenerateStatements(Configuration configuration, Dialect dialect, DatabaseMetadata metadata);
	}
}